package com.flycms.core.utils.web.utils;

import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;

import org.apache.logging.log4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.flycms.constant.StatusConst;
import com.flycms.core.entity.PagingParam;
import com.flycms.module.app.model.App;
import com.flycms.module.article.model.Article;
import com.flycms.module.comment.model.FlyContentType;
import com.flycms.module.comment.model.VoteType;
import com.flycms.module.qasystem.model.Answers;
import com.flycms.module.qasystem.model.Questions;
import com.flycms.module.user.model.User;

/**
 * 通用工具类
 *
 * <br/>Copyright 2020
 * <br/>All rights reserved
 * @author 沁言訫語
 * @version 2020年2月19日
 * @Date 2020年2月19日
 */

public class CommonUtils {

    private CommonUtils() {}
    
    /**
     * 对参数进行检查
     * @param errors
     * @param logger
     * @return 返回检查错误信息，无则返回null
     * @author 沁言訫語
     */
    
    public static String validParams(BindingResult errors, Logger logger) {
        if (errors.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            List<FieldError> fieldErrors = errors.getFieldErrors();
            fieldErrors.forEach(fieldError -> {
                sb.append(fieldError.getDefaultMessage()).append("\n");
                logger.error("ERROR filed is : {}, message is : {}", fieldError.getField(), fieldError.getDefaultMessage());
            });
            return sb.toString();
        }
        return null;
    }

    /**
     * Object转String，obj == null ? "" : obj.toString();
     * @param obj
     * @return
     * @author 沁言訫語
     */
    
    public static String transToString(Object obj) {
        return obj == null ? "" : obj.toString();
    }
    
    /**
     * 校验分页信息
     * @param param
     * @return
     * @author 沁言訫語
     */
    
    public static PagingParam validPageParam(PagingParam param) {
        if (param == null) {
            param = new PagingParam("", "desc", 10, 0, 10, 0);
            return param;
        }
        //order
        String order = param.getOrder();
        if (order != null && Objects.equals(order.toUpperCase(), "DESC")) {
            order = "desc";
        } else {
            order = "asc";
        }
        Integer pageSize = param.getPageSize();
        Integer pageIndex = param.getPageIndex();
        return validParam(pageIndex, pageSize);
    }
    
    public static PagingParam validParam(Integer pageIndex, Integer pageSize) {
        int offset = 0, rows = 0;
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        } else if (pageSize > 100) {
            pageSize = 100;
        }
        rows = pageSize;
        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }
        offset = (pageIndex - 1) * pageSize;
        return new PagingParam("", "", pageSize, pageIndex, rows, offset);
    }
    
    /**
     * 校验状态的合法性
     * @param status
     * @return
     * @author 沁言訫語
     */
    
    public static Integer validStatus(Integer status) {
        if (status == StatusConst.CLOSE.value() || status == StatusConst.TO_AUDIT.value()
                || status == StatusConst.LOCKED.value()
                || status == StatusConst.OPEN.value()
                || status == StatusConst.DELETE.value()) {
            return status;
        }
        return null;
    }
    
    /**
     * 将contentType信息转换为Integer代码
     * @param contentType
     * @return 对应枚举值或未找到时返回null
     * @author 沁言訫語
     */
    
    public static Integer validContentType(String contentType) {
        for (FlyContentType c : FlyContentType.values()) {
            if (c.msg().equalsIgnoreCase(contentType)) {
                return c.value();
            }
        }
        return null;
    }
    
    public static FlyContentType getContentType(String contentType) {
        for (FlyContentType c : FlyContentType.values()) {
            if (c.msg().equalsIgnoreCase(contentType)) {
                return c;
            }
        }
        return null;
    }
    
    /**
     * 将voteType信息转换为Integer代码
     * @param voteType
     * @return 对应枚举值或未找到时返回null
     * @author 沁言訫語
     */
    
    public static Integer validVoteType(String voteType) {
        for (VoteType v : VoteType.values()) {
            if (v.msg().equalsIgnoreCase(voteType)) {
                return v.value();
            }
        }
        return null;
    }
    
    public static VoteType getVoteType(String voteType) {
        for (VoteType v : VoteType.values()) {
            if (v.msg().equalsIgnoreCase(voteType)) {
                return v;
            }
        }
        return null;
    }
    
    /**
     * 获取UserID
     * @param obj
     * @return
     * @author 沁言訫語
     */
    
    public static User getOwner(Object obj) {
        User user = new User();
        if (obj instanceof Questions) {
            Questions q = ((Questions) obj);
            user.setUserId(q.getProposeUserId());
            user.setUserName(q.getUserName());
        }
        if (obj instanceof Answers) {
            Answers a = ((Answers) obj);
            user.setUserId(a.getReplyUserId());
            user.setUserName(a.getUserName());
        }
        if (obj instanceof Article) {
            Article a = ((Article) obj);
            user.setUserId(a.getUserId());
//            user.setUserName(a.get);
        }
        if (obj instanceof App) {
            App a = ((App) obj);
            user.setUserId(a.getCreatorId());
//            user.setUserName(a.get);
        }
        return user;
    }
    
    public static String getContentTitle(Object obj) {
        if (obj instanceof Questions) {
            return ((Questions) obj).getTitle();
        }
        if (obj instanceof Article) {
            return ((Article) obj).getTitle();
        }
        if (obj instanceof App) {
            return ((App) obj).getAppName();
        }
        return null;
    }
    
    /**
     * 用户{0}评论了你的{1}：{2}
     * @param args
     * @return
     * @author 沁言訫語
     */
    
    public static String getCommentMessageModel(Object... args) {
        String messagePattern = "用户{0}评论了你的{1}：{2}";
        String msg = MessageFormat.format(messagePattern, args);
        return msg;
    }
    
    public static String getCollerctMessageModel(Object... args) {
        String messagePattern = "用户{0}收藏了你的{1}";
        String msg = MessageFormat.format(messagePattern, args);
        return msg;
    }
    
    /**
     * 用户{0}点赞了你的{1}：{2}
     * @param args
     * @return
     * @author 沁言訫語
     */
    
    public static String getVoteMessageModel(Object... args) {
        String messagePattern = "用户{0}点赞了你的{1}：{2}";
        String msg = MessageFormat.format(messagePattern, args);
        return msg;
    }
    
}
